

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="John Doe">
  <meta name="keywords" content="">
  
    <meta name="description" content="@[toc] 一、抽象工厂模式知识回顾 参考笔记：设计模式 学习笔记（一）五个创建型模式 | Java 语言实现 | 工厂方法设计模式 | 抽象工厂模式 |建造者模式 | 单例模式 | 原型模式 抽象工厂：一种为访问类提供一个能创建一组相关或者相互依赖对象的接口是工厂方法的升级版本，工厂方法只生产一个等级的产品，而抽象工厂则可生产多个等级的产品。 优点：  支持同时管理多个等级产的产品 可扩展性高">
<meta property="og:type" content="article">
<meta property="og:title" content="设计模式 笔记6 _ 抽象工厂模式 在 JDK 源码中的应用 _ JDBC 知识回顾 _ java.sql 里的抽象工厂 Connection，其内部声明了不同的 Statement 抽象产品">
<meta property="og:url" content="http://example.com/2022/07/24/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%20%E7%AC%94%E8%AE%B06%20_%20%E6%8A%BD%E8%B1%A1%E5%B7%A5%E5%8E%82%E6%A8%A1%E5%BC%8F%20%E5%9C%A8%20JDK%20%E6%BA%90%E7%A0%81%E4%B8%AD%E7%9A%84%E5%BA%94%E7%94%A8%20_%20JDBC%20%E7%9F%A5%E8%AF%86%E5%9B%9E%E9%A1%BE%20_%20java.sql%20%E9%87%8C%E7%9A%84%E6%8A%BD%E8%B1%A1%E5%B7%A5%E5%8E%82%20Connection%EF%BC%8C%E5%85%B6%E5%86%85%E9%83%A8%E5%A3%B0%E6%98%8E%E4%BA%86%E4%B8%8D%E5%90%8C%E7%9A%84%20Statement%20%E6%8A%BD%E8%B1%A1%E4%BA%A7%E5%93%81/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="@[toc] 一、抽象工厂模式知识回顾 参考笔记：设计模式 学习笔记（一）五个创建型模式 | Java 语言实现 | 工厂方法设计模式 | 抽象工厂模式 |建造者模式 | 单例模式 | 原型模式 抽象工厂：一种为访问类提供一个能创建一组相关或者相互依赖对象的接口是工厂方法的升级版本，工厂方法只生产一个等级的产品，而抽象工厂则可生产多个等级的产品。 优点：  支持同时管理多个等级产的产品 可扩展性高">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img-blog.csdnimg.cn/091ec3056a224478aea1cb2ac6b54a93.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/fd9341ded7404207a9cf1948f6bc7f98.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/840001c3733b44d7aa83eb6dd2901123.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/d68004ef5f234e259715308094164eec.png#pic_center">
<meta property="article:published_time" content="2022-07-24T11:25:47.000Z">
<meta property="article:modified_time" content="2022-08-22T15:41:14.937Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="设计模式">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/091ec3056a224478aea1cb2ac6b54a93.png#pic_center">
  
  
  
  <title>设计模式 笔记6 _ 抽象工厂模式 在 JDK 源码中的应用 _ JDBC 知识回顾 _ java.sql 里的抽象工厂 Connection，其内部声明了不同的 Statement 抽象产品 - Hexo</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>尤 Ni&#39;s Blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="设计模式 笔记6 _ 抽象工厂模式 在 JDK 源码中的应用 _ JDBC 知识回顾 _ java.sql 里的抽象工厂 Connection，其内部声明了不同的 Statement 抽象产品"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        John Doe
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-07-24 19:25" pubdate>
          2022年7月24日 晚上
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          10k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          87 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">设计模式 笔记6 _ 抽象工厂模式 在 JDK 源码中的应用 _ JDBC 知识回顾 _ java.sql 里的抽象工厂 Connection，其内部声明了不同的 Statement 抽象产品</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：1 小时前
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <p>@[toc]</p>
<h1 id="一、抽象工厂模式知识回顾"><a href="#一、抽象工厂模式知识回顾" class="headerlink" title="一、抽象工厂模式知识回顾"></a>一、抽象工厂模式知识回顾</h1><hr>
<p>参考笔记：<a target="_blank" rel="noopener" href="https://blog.csdn.net/Unirithe/article/details/125745637">设计模式 学习笔记（一）五个创建型模式 | Java 语言实现 | 工厂方法设计模式 | 抽象工厂模式 |建造者模式 | 单例模式 | 原型模式</a></p>
<p>抽象工厂：一种为访问类提供一个能创建一组相关或者相互依赖对象的接口<br>是工厂方法的升级版本，工厂方法只生产一个等级的产品，而抽象工厂则可生产多个等级的产品。</p>
<p>优点：</p>
<ul>
<li>支持同时管理多个等级产的产品</li>
<li>可扩展性高，符合开闭原则</li>
</ul>
<p>缺点：</p>
<ul>
<li>由于是抽象的工厂，在增加新产品时，所有的工厂类都需要修改</li>
</ul>
<p><strong>主要组成</strong></p>
<p>1）Absract Factory 抽象工厂，提供创建产品的接口，可创建多个不同等级的产品<br>2）Concrete Factory 具体工厂，主要实现抽象产品中的多个抽象方法，完成具体产品的创建<br>3）Product 抽象产品，定义了产品的规范，描述其主要的特性和功能，一般有多个<br>4）Concrete Product 具体产品，实现了抽象产品所定义的接口，由具体工厂 Concrete Factory 来创建，与具体工厂的关系是 N : 1</p>
<p><strong>模板代码：</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 抽象产品1</span><br><span class="hljs-keyword">interface</span> <span class="hljs-title class_">Product1</span> &#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">produce</span><span class="hljs-params">()</span>;  <span class="hljs-comment">// 生产</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">sale</span><span class="hljs-params">()</span>;     <span class="hljs-comment">// 销售</span><br>&#125;<br><span class="hljs-comment">// 具体产品1</span><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">ConcreteProduct1A</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">Product1</span>&#123;<br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">produce</span><span class="hljs-params">()</span> &#123;<br>        System.out.println(<span class="hljs-string">&quot;产品1的A 生产成功&quot;</span>);<br>    &#125;<br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">sale</span><span class="hljs-params">()</span> &#123;<br>        System.out.println(<span class="hljs-string">&quot;产品1的A 出售成功&quot;</span>);<br>    &#125;<br>&#125;<br><span class="hljs-comment">// 具体产品2</span><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">ConcreteProduct2A</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">Product2</span>&#123;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">product</span><span class="hljs-params">()</span> &#123;<br>        System.out.println(<span class="hljs-string">&quot;产品2的A 生产成功&quot;</span>);<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">sale</span><span class="hljs-params">()</span> &#123;<br>        System.out.println(<span class="hljs-string">&quot;产品2的A 销售成功&quot;</span>);<br>    &#125;<br>&#125;<br><span class="hljs-comment">// 抽象产品1</span><br><span class="hljs-keyword">interface</span> <span class="hljs-title class_">Product2</span>&#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">product</span><span class="hljs-params">()</span>;  <span class="hljs-comment">// 生产</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">sale</span><span class="hljs-params">()</span>;    <span class="hljs-comment">// 销售</span><br>&#125;<br><span class="hljs-comment">// 抽象工厂</span><br><span class="hljs-keyword">interface</span> <span class="hljs-title class_">AbstractFactory</span>&#123;<br>    <span class="hljs-keyword">public</span> Product1 <span class="hljs-title function_">newProduct1</span><span class="hljs-params">()</span>;<br>    <span class="hljs-keyword">public</span> Product2 <span class="hljs-title function_">newProduct2</span><span class="hljs-params">()</span>;<br>&#125;<br><span class="hljs-comment">// 具体工厂</span><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">ConcreteFactory</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">AbstractFactory</span>&#123;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> Product1 <span class="hljs-title function_">newProduct1</span><span class="hljs-params">()</span> &#123;<br>        System.out.println(<span class="hljs-string">&quot;工厂1 开始生产 产品1...&quot;</span>);<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">ConcreteProduct1A</span>();<br>    &#125;<br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> Product2 <span class="hljs-title function_">newProduct2</span><span class="hljs-params">()</span> &#123;<br>        System.out.println(<span class="hljs-string">&quot;工厂2 开始生产 产品2...&quot;</span>);<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">ConcreteProduct2A</span>();<br>    &#125;<br>&#125;<br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Demo</span> &#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> &#123;<br>        <span class="hljs-comment">// 创建工厂</span><br>        <span class="hljs-type">ConcreteFactory</span> <span class="hljs-variable">factory</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">ConcreteFactory</span>();<br>        <span class="hljs-comment">// 生产</span><br>        <span class="hljs-type">Product1</span> <span class="hljs-variable">product1</span> <span class="hljs-operator">=</span> factory.newProduct1();<br>        <span class="hljs-type">Product2</span> <span class="hljs-variable">product2</span> <span class="hljs-operator">=</span> factory.newProduct2();<br>        product1.produce();<br>        product2.product();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<blockquote>
<p>&#x3D;&#x3D;运行结果&#x3D;&#x3D;<br>工厂1 开始生产 产品1…<br>工厂2 开始生产 产品2…<br>产品1的A 生产成功<br>产品2的A 生产成功</p>
</blockquote>
<h1 id="二、JDBC"><a href="#二、JDBC" class="headerlink" title="二、JDBC"></a>二、JDBC</h1><hr>
<p>参考资料：<a target="_blank" rel="noopener" href="https://www.w3cschool.cn/jdbc/84pl1my8.html">https://www.w3cschool.cn/jdbc/84pl1my8.html</a></p>
<p>JDBC ， Java Database Connect，即 Java数据库连接，是一种标准的 Java应用程序接口 API，由 JDK 提供，用来连接 Java编程语言和广泛的数据库。</p>
<h2 id="2-1-JDBC-的结构"><a href="#2-1-JDBC-的结构" class="headerlink" title="2.1 JDBC 的结构"></a>2.1 JDBC 的结构</h2><p>JDBC 结构图<br>![](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/img_convert/1f609d6f4ff15ba2964b72a4043dfead.jpeg#pic_center">https://img-blog.csdnimg.cn/img_convert/1f609d6f4ff15ba2964b72a4043dfead.jpeg#pic_center</a> &#x3D;60%x)</p>
<p>JDBC架构由两层处理模式组成：</p>
<ul>
<li>JDBC API：提供应用程序对 JDBC 管理器的连接</li>
<li>JDBC Driver API：提供了 JDBC  管理器对驱动程序的连接</li>
</ul>
<p><strong>常见的JDBC组件以及作用：</strong></p>
<ol>
<li>DriverManager类，管理 DB 驱动，用于建立 Java 程序和 DB 之间的连接</li>
<li>Driver接口，用于处理与 DB Server 的通信</li>
<li>Connection接口，DB 的连接对象，作为通信的上下文，是 Java 程序与 DB 通信唯一的桥梁</li>
<li>Statement接口，支持将 SQL 语句提交到 DB</li>
<li>ResultSet类，存储SQL查询的结果的迭代器</li>
<li>SQLException类，处理 DB 操作相关的异常</li>
</ol>
<h2 id="2-2-JDBC-驱动程序"><a href="#2-2-JDBC-驱动程序" class="headerlink" title="2.2 JDBC 驱动程序"></a>2.2 JDBC 驱动程序</h2><p>为进一步了解 JDBC 的使用原理，我们先看看它的驱动程序。</p>
<p>参考：<a target="_blank" rel="noopener" href="https://www.w3cschool.cn/jdbc/j3xk1myd.html">https://www.w3cschool.cn/jdbc/j3xk1myd.html</a></p>
<p>JDBC 驱动实现了 JDBC API 中定义的接口，该接口用于与 DB Server 进行交互</p>
<p>JDK 的 java.sql 包中定义了各种 DB 类的行为以及实现</p>
<p>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/f9d38d51b706444da3939e7883ec7b8c.png#">https://img-blog.csdnimg.cn/f9d38d51b706444da3939e7883ec7b8c.png#</a> &#x3D;50%x)</p>
<p>JDK 提供的这些接口和类，都将在第三方驱动程序中进行实现以及拓展，其中最主要的就是 Driver 驱动接口，每一个 JDBC  驱动都必须实现这个接口，因为它是连接 DB 的核心。</p>
<h3 id="2-2-1-JDBC-驱动的不同类型"><a href="#2-2-1-JDBC-驱动的不同类型" class="headerlink" title="2.2.1 JDBC 驱动的不同类型"></a>2.2.1 JDBC 驱动的不同类型</h3><p>由于操作系统和 Java 运行所在的硬件平台的不同，JDBC 驱动 由 Sun 公司分为了四种类型。</p>
<h4 id="1-JDBC-ODBC-桥驱动程序【了解即可】"><a href="#1-JDBC-ODBC-桥驱动程序【了解即可】" class="headerlink" title="1. JDBC-ODBC 桥驱动程序【了解即可】"></a>1. JDBC-ODBC 桥驱动程序【了解即可】</h4><p>ODBC，Open Database Connectivity ，开放数据库互联，是微软公司开放服务结构 WOSA 中有关数据库的一个组成部分，建立了一组规范，并提供了对 DB 进行访问的标准API。</p>
<p>JDBC 桥接器用来访问安装在客户机上的 ODBC 驱动程序，为了使用 ODBC，需在目标数据库上配置系统数据源名称（DSN）<br>在 Java 刚出来时，这个驱动程序很有用，当时大多数数据库支支持 ODBC，但目前该类型几乎不使用<br>结构图（图片来自网络）：</p>
<p><img src="https://img-blog.csdnimg.cn/091ec3056a224478aea1cb2ac6b54a93.png#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<h4 id="2-JDBC-Native-API"><a href="#2-JDBC-Native-API" class="headerlink" title="2. JDBC-Native API"></a>2. JDBC-Native API</h4><p>这种驱动程序的特点是支持将 JDBC API 调用转换成原生的 C&#x2F;C++ 的 API 调用，对数据库来说具有唯一性，使用方式和 JDBC-ODBC 类似，该供应商的驱动程序必须安装在每一台客户机<br>结构图（图片来自网络）：<br><img src="https://img-blog.csdnimg.cn/fd9341ded7404207a9cf1948f6bc7f98.png#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<h4 id="3-JDBC-Net-纯-Java-实现"><a href="#3-JDBC-Net-纯-Java-实现" class="headerlink" title="3. JDBC-Net 纯 Java 实现"></a>3. JDBC-Net 纯 Java 实现</h4><p>这种驱动程序一般使用三层结构来访问 DB，JDBC Client 使用标准的 Web Socket 与 中间件应用服务器进行通信，网络套接字的相关信息被中间件应用服务器 转换为 DB 管理系统所要求调用的格式，并转发到 DB Server。<br>特点：灵活，不同于之前两种类型，无需在客户机上安装，而且单个驱动程序能提供多个 DB</p>
<p>结构图 （图片来自网络）：<br><img src="https://img-blog.csdnimg.cn/840001c3733b44d7aa83eb6dd2901123.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<h4 id="4-100-纯-Java-实现-JDBC-驱动"><a href="#4-100-纯-Java-实现-JDBC-驱动" class="headerlink" title="4. 100% 纯 Java 实现 JDBC 驱动"></a>4. 100% 纯 Java 实现 JDBC 驱动</h4><p>这种驱动程序，实现了使用 Java 的驱动程序 通过 Socket 连接与服务端的 DB 进行通信。<br>特点：</p>
<ul>
<li>性能最高，由第三方自身提供</li>
<li>比第三种灵活，无需在客户端或服务端上安装特殊的软件</li>
<li>驱动程序支持动态下载</li>
</ul>
<p>结构图（图片来自网络）：<br><img src="https://img-blog.csdnimg.cn/d68004ef5f234e259715308094164eec.png#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>我们接下来要使用连接 MySQL 的驱动器就是这一种，MySQL Connector&#x2F;J 的驱动程序是由 MySQL 官方提供的。</p>
<h5 id="如何选择驱动程序"><a href="#如何选择驱动程序" class="headerlink" title="如何选择驱动程序"></a>如何选择驱动程序</h5><ul>
<li>Oracle、MySQL、Sysbase 或 IBM ，首选驱动类型是第四种，即由第三方使用纯Java提供</li>
<li>当 Java 应用程序同时访问多种 DB ，首选的驱动程序是第三种，即使用中间件</li>
<li>类型2 的驱动程序是只有当选择的 DB 既没有提供类型3 ，也没有提供类型4 时的选择。</li>
<li>类型1 几乎不使用</li>
</ul>
<h2 id="2-3-JDBC-使用案例"><a href="#2-3-JDBC-使用案例" class="headerlink" title="2.3 JDBC 使用案例"></a>2.3 JDBC 使用案例</h2><p>JDBC 使用案例分为以下几个步骤，这里以 MySQL 5.7.36 为例：</p>
<p>1）准备数据库环境，包括测试查询的表<br>2）准备驱动包，导入数据库的操作包，导入有需要进行 DB 编程的 JDBC 类的包，比如：JDK8提供的 java.sql.*，也可以导入它的封装框架，例如 MyBatis，这里以前者的MySQL 为主<br>3）获取 Connection 连接对象，通过驱动管理器获取连接  DriverManager.getConnection<br>4）执行查询，通过 Connection对象，创建并使用 Statement 接口实现 SQL 语句的查询<br>5）提取结果，使用 ResultSet 接口实现类接收 Statement 执行的结果，使用时转为 ResultSet 接口即可<br>6）关闭资源，最后需关闭 DB 相关的资源，防止资源的浪费</p>
<ol start="0">
<li><p>引入驱动包依赖</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-comment">&lt;!-- Lombok 可提供 匹配Setter、Getter 和日志等功能 --&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>  <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.projectlombok<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>  <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>lombok<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>  <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>1.18.24<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br><br><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>  <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>mysql<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>  <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>mysql-connector-java<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>  <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>8.0.25<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br></code></pre></td></tr></table></figure>
</li>
<li><p>准备数据表</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">SET</span> NAMES utf8mb4;<br><span class="hljs-keyword">SET</span> FOREIGN_KEY_CHECKS <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;<br><br><span class="hljs-comment">-- ----------------------------</span><br><span class="hljs-comment">-- Table structure for t_user</span><br><span class="hljs-comment">-- ----------------------------</span><br><span class="hljs-keyword">DROP</span> <span class="hljs-keyword">TABLE</span> IF <span class="hljs-keyword">EXISTS</span> `t_user`;<br><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> `t_user`  (<br>  `user_id` <span class="hljs-type">int</span>(<span class="hljs-number">11</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-keyword">NULL</span>,<br>  `user_username` <span class="hljs-type">varchar</span>(<span class="hljs-number">50</span>) <span class="hljs-type">CHARACTER</span> <span class="hljs-keyword">SET</span> utf8mb4 <span class="hljs-keyword">COLLATE</span> utf8mb4_general_ci <span class="hljs-keyword">NULL</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-keyword">NULL</span>,<br>  `user_password` <span class="hljs-type">varchar</span>(<span class="hljs-number">100</span>) <span class="hljs-type">CHARACTER</span> <span class="hljs-keyword">SET</span> utf8mb4 <span class="hljs-keyword">COLLATE</span> utf8mb4_general_ci <span class="hljs-keyword">NULL</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-keyword">NULL</span>,<br>  <span class="hljs-keyword">PRIMARY</span> KEY (`user_id`) <span class="hljs-keyword">USING</span> BTREE<br>) ENGINE <span class="hljs-operator">=</span> InnoDB <span class="hljs-type">CHARACTER</span> <span class="hljs-keyword">SET</span> <span class="hljs-operator">=</span> utf8mb4 <span class="hljs-keyword">COLLATE</span> <span class="hljs-operator">=</span> utf8mb4_general_ci ROW_FORMAT <span class="hljs-operator">=</span> <span class="hljs-keyword">Dynamic</span>;<br><br><span class="hljs-comment">-- ----------------------------</span><br><span class="hljs-comment">-- Records of t_user</span><br><span class="hljs-comment">-- ----------------------------</span><br><span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> `t_user` <span class="hljs-keyword">VALUES</span> (<span class="hljs-number">1</span>, <span class="hljs-string">&#x27;孙悟空&#x27;</span>, <span class="hljs-string">&#x27;123456&#x27;</span>);<br><span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> `t_user` <span class="hljs-keyword">VALUES</span> (<span class="hljs-number">2</span>, <span class="hljs-string">&#x27;唐僧&#x27;</span>, <span class="hljs-string">&#x27;123123&#x27;</span>);<br><span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> `t_user` <span class="hljs-keyword">VALUES</span> (<span class="hljs-number">3</span>, <span class="hljs-string">&#x27;白骨精&#x27;</span>, <span class="hljs-string">&#x27;123456&#x27;</span>);<br><br><span class="hljs-keyword">SET</span> FOREIGN_KEY_CHECKS <span class="hljs-operator">=</span> <span class="hljs-number">1</span>;<br></code></pre></td></tr></table></figure>
</li>
<li><p>准备实体类 User，用于接收查询的结果</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">import</span> lombok.AllArgsConstructor;<br><span class="hljs-keyword">import</span> lombok.Data;<br><span class="hljs-keyword">import</span> lombok.NoArgsConstructor;<br><br><span class="hljs-meta">@Data</span><br><span class="hljs-meta">@AllArgsConstructor</span><br><span class="hljs-meta">@NoArgsConstructor</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">User</span> &#123;<br>    <span class="hljs-keyword">private</span> Integer id;<br>    <span class="hljs-keyword">private</span> String username;<br>    <span class="hljs-keyword">private</span> String password;<br>&#125;<br><br></code></pre></td></tr></table></figure>
</li>
<li><p>建立 JDBC 连接类，并提供一个查询用户信息的方法 list()</p>
</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.bbs.uni;<br><br><span class="hljs-keyword">import</span> com.bbs.uni.entity.User;<br><span class="hljs-keyword">import</span> lombok.extern.slf4j.Slf4j;<br><br><span class="hljs-keyword">import</span> java.sql.*;<br><span class="hljs-keyword">import</span> java.util.ArrayList;<br><span class="hljs-keyword">import</span> java.util.List;<br><span class="hljs-keyword">import</span> java.util.Map;<br><span class="hljs-meta">@Slf4j</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Demo</span>&#123;<br>    <span class="hljs-comment">// 定义数据库信息</span><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">String</span> <span class="hljs-variable">JDBC_DRIVER</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;com.mysql.cj.jdbc.Driver&quot;</span>;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">String</span> <span class="hljs-variable">DB_URL</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;jdbc:mysql://localhost:3306/bbsuni&quot;</span>;<br>    <span class="hljs-comment">// 数据库用户名和密码</span><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">String</span> <span class="hljs-variable">USERNAME</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;root&quot;</span>;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">String</span> <span class="hljs-variable">PASSWORD</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;woaini&quot;</span>;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-type">Connection</span> <span class="hljs-variable">connection</span> <span class="hljs-operator">=</span> <span class="hljs-literal">null</span>;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-type">Statement</span> <span class="hljs-variable">stmt</span> <span class="hljs-operator">=</span> <span class="hljs-literal">null</span>;<br>    <span class="hljs-keyword">static</span> &#123;<br>        <span class="hljs-keyword">try</span>&#123;<br>            <span class="hljs-comment">// 加载驱动</span><br>            Class.forName(JDBC_DRIVER);<br>            <span class="hljs-comment">// 记录连接对象</span><br>            connection = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);<br>            <span class="hljs-comment">// 创建 SQL 提交器</span><br>            stmt = connection.createStatement();<br>        &#125; <span class="hljs-keyword">catch</span> (ClassNotFoundException e) &#123;<br>            <span class="hljs-comment">// 未找到驱动类</span><br>            log.error(<span class="hljs-string">&quot;JDBC Driver isn&#x27;t found: &#123;&#125;&quot;</span>, JDBC_DRIVER);<br>            e.printStackTrace();<br>        &#125; <span class="hljs-keyword">catch</span> (SQLException throwables) &#123;<br>            <span class="hljs-comment">// 建立 DB 连接失败</span><br>            log.error(<span class="hljs-string">&quot;Fail to connect the DB By username=&#123;&#125;, password=&#123;&#125;&quot;</span><br>            ,USERNAME, PASSWORD);<br>            throwables.printStackTrace();<br>        &#125;<br>    &#125;<br>    <span class="hljs-comment">// 查询用户表</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> List&lt;User&gt; <span class="hljs-title function_">select</span><span class="hljs-params">(String sql)</span>&#123;<br>        <span class="hljs-keyword">try</span> &#123;<br>            <span class="hljs-type">ResultSet</span> <span class="hljs-variable">rs</span> <span class="hljs-operator">=</span> stmt.executeQuery(sql);<br>            List&lt;User&gt; users = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayList</span>&lt;&gt;();<br>            <span class="hljs-comment">// 遍历迭代器</span><br>            <span class="hljs-keyword">while</span>(rs.next())&#123;<br>                users.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">User</span>(<br>                            rs.getInt(<span class="hljs-string">&quot;user_id&quot;</span>),<br>                            rs.getString(<span class="hljs-string">&quot;user_username&quot;</span>),<br>                            rs.getString(<span class="hljs-string">&quot;user_password&quot;</span>)));<br>            &#125;<br>            rs.close(); <span class="hljs-comment">// 关闭流</span><br>            <span class="hljs-keyword">return</span> users;<br>        &#125; <span class="hljs-keyword">catch</span> (SQLException throwables) &#123;<br>            log.error(<span class="hljs-string">&quot;Fail to execute sql: &#123;&#125;&quot;</span>, sql);<br>            throwables.printStackTrace();<br>        &#125;<br>        <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;<br>    &#125;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">closeDB</span><span class="hljs-params">()</span>&#123;<br>        <span class="hljs-keyword">try</span>&#123;<br>            <span class="hljs-keyword">if</span>(stmt != <span class="hljs-literal">null</span>) stmt.close();<br>            <span class="hljs-keyword">if</span>(connection != <span class="hljs-literal">null</span>) connection.close();<br>        &#125; <span class="hljs-keyword">catch</span> (SQLException throwables) &#123;<br>            log.error(<span class="hljs-string">&quot;Fail to close the Statement or Connection&quot;</span>);<br>            throwables.printStackTrace();<br>        &#125;<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> &#123;<br>        log.debug(<span class="hljs-string">&quot;Try to connect the mysql, result is &lt;&#123;&#125;&gt;&quot;</span>, connection);<br>        List&lt;User&gt; users = select(<span class="hljs-string">&quot;select * from t_user&quot;</span>);<br>        <span class="hljs-keyword">assert</span> users != <span class="hljs-literal">null</span> &amp;&amp; users.size() &gt; <span class="hljs-number">0</span> : <span class="hljs-string">&quot;[WARNING] The Query Result is Empty.&quot;</span>;<br>        users.forEach(System.out::println);<br>        closeDB();<br>        log.info(<span class="hljs-string">&quot;DB had closed&quot;</span>);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<blockquote>
<p>运行结果<br>09:27:44.039 [main] DEBUG com.bbs.uni.Demo - Try to connect the mysql, result is &lt;com.mysql.cj.jdbc.ConnectionImpl@43738a82&gt;<br>User(id&#x3D;1, username&#x3D;孙悟空, password&#x3D;123456)<br>User(id&#x3D;2, username&#x3D;唐僧, password&#x3D;123123)<br>User(id&#x3D;3, username&#x3D;白骨精, password&#x3D;123456)<br>09:27:44.052 [main] INFO com.bbs.uni.Demo - DB had closed</p>
</blockquote>
<h1 id="三、JDK源码中的抽象工厂设计模式"><a href="#三、JDK源码中的抽象工厂设计模式" class="headerlink" title="三、JDK源码中的抽象工厂设计模式"></a>三、JDK源码中的抽象工厂设计模式</h1><hr>
<p>在上个使用案例中，我们使用了MySQL提供的 JDBC 驱动程序，其内部实现了 JDK 的 <code>java.sql</code> 包中所定义的进行 JDBC 操作的接口，这属于四种 JDBC 驱动程序中的最后一种，最灵活最高效。</p>
<p>接下来我们先从比较关键的 Connection接口 （数据库连接对象）来了解源码：</p>
<p>JDK 源码提供的 Connection 接口：Connection.java</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 只列举几个关键的方法</span><br><br><span class="hljs-keyword">package</span> java.sql;<br><br><span class="hljs-keyword">import</span> java.util.Map;<br><span class="hljs-keyword">import</span> java.util.Properties;<br><span class="hljs-keyword">import</span> java.util.concurrent.Executor;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title class_">Connection</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_">Wrapper</span>, AutoCloseable &#123;<br>    <span class="hljs-comment">// 提供 SQL语句 的执行对象</span><br>    Statement <span class="hljs-title function_">createStatement</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> SQLException;<br>    <span class="hljs-comment">// 提供支持预编译的SQL语句的执行对象</span><br>    PreparedStatement <span class="hljs-title function_">prepareStatement</span><span class="hljs-params">(String var1)</span> <span class="hljs-keyword">throws</span> SQLException;<br>    <span class="hljs-comment">//  提供支持存储过程的SQl语句的执行对象</span><br>    CallableStatement <span class="hljs-title function_">prepareCall</span><span class="hljs-params">(String var1)</span> <span class="hljs-keyword">throws</span> SQLException;<br>    ...<br>&#125;<br></code></pre></td></tr></table></figure>
<p>MSQL提供的 JDBC 驱动源码：Driver.java</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs java"><br><span class="hljs-keyword">package</span> com.mysql.cj.jdbc;<br><br><span class="hljs-keyword">import</span> java.sql.DriverManager;<br><span class="hljs-keyword">import</span> java.sql.SQLException;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Driver</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_">NonRegisteringDriver</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">java</span>.sql.Driver &#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-title function_">Driver</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> SQLException &#123;<br>    &#125;<br>    <span class="hljs-comment">// 单例模式, 饿汉式，注册 DriverManager</span><br>    <span class="hljs-keyword">static</span> &#123;<br>        <span class="hljs-keyword">try</span> &#123;<br>            DriverManager.registerDriver(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Driver</span>());<br>        &#125; <span class="hljs-keyword">catch</span> (SQLException var1) &#123;<br>            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RuntimeException</span>(<span class="hljs-string">&quot;Can&#x27;t register driver!&quot;</span>);<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>JDK 源码提供的 DriverManager 接口 DriverManager.java</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> java.sql;<br>...<br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">DriverManager</span> &#123;<br>    <span class="hljs-comment">// 注册的 JDBC 驱动程序列表</span><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> CopyOnWriteArrayList&lt;DriverInfo&gt; registeredDrivers = <span class="hljs-keyword">new</span> <span class="hljs-title class_">CopyOnWriteArrayList</span>();<br>    ... <br>&#125;<br></code></pre></td></tr></table></figure>
<p>从上面的源代码可以看出，Connection 接口是一个经典的抽象工厂，而 Statement、PreparedState、CallableStatement 就是 Connection 这个抽象工厂中提供的三个抽象产品。</p>
<p>驱动程序提供的 Driver 接口实现类 起到了客户端的作用，我们只需把 Driver 注册到 DriverManager，就可以生成对应的 Connection 连接对象，每次操作数据库时就通过 Connection 接口，可以支持不同 DB 的 不同驱动程序进行创建</p>
<p>这些抽象工厂与抽象产品均由对应的数据库驱动实现，接下来以 MYSQL 的驱动为例：<br><strong>1）Connection</strong><br>Connection 接口的部分实现如图：<br>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/f70568a115424af38d0228ea1e3b21d2.png#">https://img-blog.csdnimg.cn/f70568a115424af38d0228ea1e3b21d2.png#</a> &#x3D;40%x)</p>
<p><strong>2）Statement</strong><br>Statement 接口的部分实现如图：<br>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/167e615e00ac4dcead34641e6b9779d1.png#">https://img-blog.csdnimg.cn/167e615e00ac4dcead34641e6b9779d1.png#</a> &#x3D;40%x)</p>
<p><strong>3）PreparedStatement</strong><br>PreparedStatement 的部分实现如图：<br>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/c0180df12f1145e4bae995cccd205bb2.png#">https://img-blog.csdnimg.cn/c0180df12f1145e4bae995cccd205bb2.png#</a> &#x3D;40%x)</p>
<p><strong>4）CallableStatement</strong><br>CallableStatement 的部分实现如图：<br>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/2b15f17f4f964f9798f8f017f03e520f.png#">https://img-blog.csdnimg.cn/2b15f17f4f964f9798f8f017f03e520f.png#</a> &#x3D;80%x)</p>
<p><strong>5）JDBC 抽象工厂 UML 图</strong></p>
<p>我们可将以上继承关系简化成一个完整的抽象工厂 UML 图：<br>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/938172180332475eaeb46812c7b8d7e3.png#">https://img-blog.csdnimg.cn/938172180332475eaeb46812c7b8d7e3.png#</a> &#x3D;80%x)</p>
<p>至此，抽象工厂模式在JDK源码里的运用学习结束。</p>
<h1 id="参-考-资-料"><a href="#参-考-资-料" class="headerlink" title="参  考  资  料"></a>参  考  资  料</h1><hr>
<p>[1] <a target="_blank" rel="noopener" href="https://www.w3cschool.cn/jdbc/84pl1my8.html">JDBC 简介_W3CSchool</a><br>[2] <a target="_blank" rel="noopener" href="https://www.w3cschool.cn/jdbc/j3xk1myd.html">JDBC 驱动类型_W3CSchool</a></p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" class="category-chain-item">设计模式</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">#设计模式</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>设计模式 笔记6 _ 抽象工厂模式 在 JDK 源码中的应用 _ JDBC 知识回顾 _ java.sql 里的抽象工厂 Connection，其内部声明了不同的 Statement 抽象产品</div>
      <div>http://example.com/2022/07/24/设计模式 笔记6 _ 抽象工厂模式 在 JDK 源码中的应用 _ JDBC 知识回顾 _ java.sql 里的抽象工厂 Connection，其内部声明了不同的 Statement 抽象产品/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>John Doe</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年7月24日</div>
        </div>
      
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/07/24/Web%E5%BC%80%E5%8F%91%20%E8%BA%AB%E4%BB%BD%E9%AA%8C%E8%AF%812%20_%20SpringBoot%20%E6%95%B4%E5%90%88%20JWT%20_%20%E5%89%8D%E5%90%8E%E7%AB%AF%E5%88%86%E7%A6%BB%E7%AD%96%E7%95%A5%20_%20%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98%E7%9A%84%E5%87%BA%E7%8E%B0%E4%B8%8E%E8%A7%A3%E5%86%B3/" title="Web开发 身份验证2 _ SpringBoot 整合 JWT _ 前后端分离策略 _ 跨域问题的出现与解决">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Web开发 身份验证2 _ SpringBoot 整合 JWT _ 前后端分离策略 _ 跨域问题的出现与解决</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/07/24/Vue2%20%E7%AC%94%E8%AE%B03%20Vue2%E4%B8%89%E7%A7%8Dslot%E6%8F%92%E6%A7%BD%E7%9A%84%E6%A6%82%E5%BF%B5%E4%B8%8E%E8%BF%90%E7%94%A8%20_%20ES6%20%E5%AF%B9%E8%B1%A1%E7%9A%84%E8%A7%A3%E6%9E%84%E8%B5%8B%E5%80%BC%20_%20%E5%9F%BA%E4%BA%8EVue2%E4%BD%BF%E7%94%A8axios%E5%8F%91%E9%80%81%E8%AF%B7%E6%B1%82%E5%AE%9E%E7%8E%B0GitHub%E6%A1%88%E4%BE%8B%20_%20%E6%B5%8F%E8%A7%88%E5%99%A8%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98%E4%B8%8E%E8%A7%A3%E5%86%B3/" title="Vue2 笔记3 Vue2三种slot插槽的概念与运用 _ ES6 对象的解构赋值 _ 基于Vue2使用axios发送请求实现GitHub案例 _ 浏览器跨域问题与解决">
                        <span class="hidden-mobile">Vue2 笔记3 Vue2三种slot插槽的概念与运用 _ ES6 对象的解构赋值 _ 基于Vue2使用axios发送请求实现GitHub案例 _ 浏览器跨域问题与解决</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
